package com.example.task4.listener;

import jakarta.servlet.ServletContext;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

@WebListener
public class OnlineUserListener implements HttpSessionListener {

    private static final String ATTR_ONLINE_COUNT = "onlineCount";
    private final AtomicInteger counter = new AtomicInteger(0);

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        int now = counter.incrementAndGet();
        ServletContext ctx = se.getSession().getServletContext();
        ctx.setAttribute(ATTR_ONLINE_COUNT, now);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        int now = counter.decrementAndGet();
        if (now < 0) now = 0;
        ServletContext ctx = se.getSession().getServletContext();
        ctx.setAttribute(ATTR_ONLINE_COUNT, now);
    }
}

